﻿using System;
using System.Collections.Generic;
using System.Linq;
using BoldBrick.Core.Logging;
using BoldBrick.SharePoint.CommonControls.DataObjects.Base;
using Microsoft.SharePoint;

namespace BoldBrick.SharePoint.CommonControls.Extensions
{
	/// <summary>
	/// Extension class for <see cref="SPFolder"/> objects
	/// </summary>
	public static class SPFolderEx
	{
		private static readonly ILogger log = Logger.GetLogger(typeof (SPFolderEx));

		/// <summary>
		/// Sets allowed content types for the folder
		/// </summary>
		/// <param name="folder">Folder to set</param>
		/// <param name="list">Parent list of the folder</param>
		/// <param name="siteContentTypeIDs">Site content types IDs</param>
		public static void SetContentTypes(this SPFolder folder, SPList list, params SPContentTypeId[] siteContentTypeIDs)
		{
			// get list of list content types based on site content types
			List<SPContentType> spContentTypes = siteContentTypeIDs
				.Select(contentTypeID => list.ContentTypes.GetChildContentType(contentTypeID))
				.Where(spContentType => spContentType != null)
				.ToList();

			try
			{
				log.Write(LogLevel.Info, "Update folder: {0}", folder.ServerRelativeUrl);

				folder.UniqueContentTypeOrder = spContentTypes;
				folder.Update();
			}
			catch (Exception ex)
			{
				log.Write(LogLevel.Error, ex, "Folder update failed.");
			}
		}
	}
}
